package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/url"
)

// 网易云歌曲信息结构体
type NMusic struct {
	Songs []Songs `json:"songs"`
}

// 歌手
type Artists struct {
	Name string `json:"name"`
}

// 专辑
type Album struct {
	Name       string    `json:"name"`
	ID         int       `json:"id"`
	BlurPicURL string    `json:"blurPicUrl"`
	PicURL     string    `json:"picUrl"`
	Artists    []Artists `json:"artists"`
}

// 歌曲
type Songs struct {
	Name    string    `json:"name"`
	ID      int       `json:"id"`
	Artists []Artists `json:"artists"`
	Album   Album     `json:"album"`
}

// 获取歌手
func (n *NMusic) getSinger() (singer string) {
	for _, item := range n.Songs[0].Artists {
		if len(n.Songs[0].Artists) > 1 {
			singer += item.Name + "、"
		} else {
			singer = item.Name
		}
	}
	return singer
}

// 获取歌曲名称
func (n *NMusic) getName() string {
	return n.Songs[0].Name
}

// 获取歌曲名称
func (n *NMusic) getAlbumName() string {
	return n.Songs[0].Album.Name
}

// 获取歌曲封面
func (n *NMusic) getPic() string {
	return n.Songs[0].Album.BlurPicURL
}

// 获取歌曲下载地址
func (n *NMusic) getDownloadURL() string {
	return fmt.Sprintf("http://music.163.com/song/media/outer/url?id=%d.mp3", n.Songs[0].ID)
}

// 生成通用歌曲信息
func parseByNetEasy(musicURL string) *Music {

	songURL, _ := url.ParseRequestURI(musicURL)

	songURLQuery := songURL.Query()

	music, _ := getMusicInfo(songURLQuery.Get("id"))

	return &Music{
		Name:     music.getName(),
		URL:      music.getDownloadURL(),
		AlbumPic: music.getPic(),
		Album:    music.getAlbumName(),
		Singer:   music.getSinger(),
	}
}

// 获取音乐详情接口
// http://music.163.com/api/song/detail/?ids=[27588744]&csrf_token=
func getMusicInfo(id string) (music *NMusic, err error) {

	infoURL := fmt.Sprintf("http://music.163.com/api/song/detail/?ids=[%s]", id)

	response := Get(infoURL)

	defer response.Body.Close()

	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("读取页面信息失败")
		return
	}

	err = json.Unmarshal(result, &music)

	if err != nil {
		fmt.Println(err)
		return
	}

	return music, nil
}
